package gov.pbc.nn.kjgl.train.dao;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.bstek.bdf2.core.business.IDept;
import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Page;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.bdf.service.DeptService;
import gov.pbc.nn.core.dao.AbstractHibernateDao;
import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.Constants;
import gov.pbc.nn.kjgl.entity.MeetingDept;
import gov.pbc.nn.kjgl.entity.MeetingUser;
import gov.pbc.nn.kjgl.entity.TrainingDept;
import gov.pbc.nn.kjgl.entity.TrainingPlan;
import gov.pbc.nn.kjgl.entity.TrainingScore;
import gov.pbc.nn.kjgl.entity.TrainingUser;
import gov.pbc.nn.kjgl.xkyyh.entity.TrainDept;

@Repository
public class TrainPlanDao extends AbstractHibernateDao {

	@Autowired
	private DeptService deptService;

	/**
	 * 查询所有培训计划
	 * 
	 * @param page
	 */
	public void getAll(Page<TrainingPlan> page) {
		DetachedCriteria query = DetachedCriteria.forClass(TrainingPlan.class);
		query.add(Restrictions.or(Restrictions.eq("invalid", false), Restrictions.isNull("invalid")));
		query.add(Restrictions.eq("createUser", ContextHolder.getLoginUserName()));
		this.pagingQuery(page, query);
	}

	/**
	 * 保存 修改 培训计划
	 * 
	 * @param list
	 */
	public void save(List<TrainingPlan> list) {
		for (TrainingPlan trainingPlan : list) {
			EntityState s = EntityUtils.getState(trainingPlan);
			if (s == EntityState.NEW) {
				trainingPlan.setState(1);
				trainingPlan.setProjectId(getProjectId());
				trainingPlan.setApplyDeptId(ContextHolder.getLoginUser().getDepts().get(0).getId());
				trainingPlan.setApplyUser(ContextHolder.getLoginUserName());
				this.save(trainingPlan);
			} else if (s == EntityState.MODIFIED) {
				this.update(trainingPlan);
			}
		}
	}

	/**
	 * 单独提交保存
	 * 
	 * @param list
	 */

	public void TrainPlanTJ(List<TrainingPlan> list) {
		for (TrainingPlan trainingPlan : list) {
			EntityState s = EntityUtils.getState(trainingPlan);
			if (s == EntityState.NEW) {
				trainingPlan.setState(5);
				trainingPlan.setProjectId(getProjectId());
				trainingPlan.setApplyDeptId(ContextHolder.getLoginUser().getDepts().get(0).getId());
				trainingPlan.setApplyUser(ContextHolder.getLoginUserName());
				this.save(trainingPlan);
			} else if (s == EntityState.MODIFIED) {
				trainingPlan.setState(5);
				this.update(trainingPlan);
			}
		}
	}

	/**
	 * 删除培训计划（可批量删除）
	 * 
	 * @param id
	 */
	public void delete(String id) {
		this.delete(id, TrainingPlan.class);
		// 删除对应的TrainingUser
		List<TrainingUser> ls = getTrainingUser(id);
		if (ls != null) {
			for (TrainingUser m : ls) {
				this.delete(m);
			}
		}
		// 删除对应的TrainingDept
		List<TrainingDept> lsd = getTrainingDeptById(id);
		if (lsd != null) {
			for (TrainingDept m : lsd) {
				this.delete(m);
			}
		}
		// 删除对应的TrainingDept
		List<TrainingScore> score = getTrainingScoreById(id);
		if (score != null) {
			for (TrainingScore m : score) {
				this.delete(m);
			}
		}
	}

	public List<TrainingUser> getTrainingUser(String id) {
		String hql = "from TrainingUser where busKey=:id and invalid=false";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<TrainingUser> ls = this.query(hql, map);
		if (ls.size() > 0) {
			return ls;
		}
		return null;
	}

	public List<TrainingDept> getTrainingDeptById(String id) {
		DetachedCriteria query = DetachedCriteria.forClass(TrainingDept.class);
		query.add(Restrictions.or(Restrictions.eq("invalid", false), Restrictions.isNull("invalid")));
		query.add(Restrictions.eq("busKey", id));
		List<TrainingDept> ls = (List<TrainingDept>) this.query(query);
		if (ls.size() > 0) {
			return ls;
		}
		return null;
	}

	public List<TrainingScore> getTrainingScoreById(String id) {
		DetachedCriteria query = DetachedCriteria.forClass(TrainingScore.class);
		query.add(Restrictions.or(Restrictions.eq("invalid", false), Restrictions.isNull("invalid")));
		query.add(Restrictions.eq("projectId", id));
		List<TrainingScore> ls = (List<TrainingScore>) this.query(query);
		if (ls.size() > 0) {
			return ls;
		}
		return null;
	}

	/**
	 * 提交培训计划 提交状态（5）
	 * 
	 * @param id
	 */
	public void updateStateTj(String id) {
		TrainingPlan trainPlan = this.getTrainPlanById(id);
		trainPlan.setState(5);
		this.update(trainPlan);
	}

	/**
	 * 撤销培训计划 撤销状态（20）
	 * 
	 * @param id
	 */
	public void updateStateRem(String id) {
		TrainingPlan trainPlan = this.getTrainPlanById(id);
		trainPlan.setState(20);
		this.update(trainPlan);
	}

	/**
	 * 撤销培训计划 完成状态（20）
	 * 
	 * @param id
	 */
	public void finish(String id) {
		TrainingPlan trainPlan = this.getTrainPlanById(id);
		trainPlan.setState(100);
		this.update(trainPlan);
	}

	/**
	 * 根据id 查询培训计划
	 * 
	 * @param id
	 * @return
	 */
	public TrainingPlan getTrainPlanById(String id) {
		String hql = "from TrainingPlan where invalid=false and id=:id";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<TrainingPlan> ls = this.query(hql, map);
		if (ls.size() > 0) {
			return ls.get(0);
		} else {
			return null;
		}
	}

	/**
	 * 根据id 查询培训计划部门
	 * 
	 * @param id
	 * @return
	 */
	public TrainingDept getTrainDeptById(String deptId, String id) {
		String hql = "from TrainingDept where invalid=false and busKey=:id and deptId=:deptId";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		map.put("deptId", deptId);
		List<TrainingDept> ls = this.query(hql, map);
		if (ls.size() > 0) {
			return ls.get(0);
		} else {
			return null;
		}
	}

	/**
	 * 查询 当前登录人所在处室 有 培训审核员 角色的 人员
	 * 
	 * @return
	 */

	public List<Map<String, Object>> getAssessor() {
		Dept dept = (Dept) ContextHolder.getLoginUser().getDepts().get(0);
		List<IUser> users = SecurityUtils.getUserByRoleForDeptWithChildren(dept.getCDept().getId(),
				Constants.ROLE_PXSHY);
		List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();
		// if (users.size() > 0) {
		for (IUser u : users) {
			// List<IDept> lsDept = deptService.loadUserDepts(u.getUsername());
			// if (lsDept.size() > 0) {
			// IDept depts = lsDept.get(0);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("cname", u.getCname());
			map.put("username", u.getUsername());
			map.put("dept", EntityUtils.getValue(u, "deptName"));
			ls.add(map);
			// }
		}
		// } else {
		// ls = null;
		// }
		return ls;
	}

	/**
	 * 发布任务 传TrainingPlan ，修改状态15（发布），
	 * 
	 * @param parameter
	 * @throws ParseException
	 */

	public void releaseMeeting(Map<String, Object> parameter) throws ParseException {
		// state设置为15表示发布
		TrainingPlan trainPlan = this.getTrainPlanById((String) parameter.get("trainPlanId"));
		trainPlan.setState(15);
		this.update(trainPlan);

		                                                            

		List<String> ids = (List<String>) parameter.get("ids");
		List<String> names = (List<String>) parameter.get("names");

		for (int i = 0; i < ids.size(); i++) {
			if (this.getTrainDeptById(ids.get(i), trainPlan.getId()) == null) {
				TrainingDept td = new TrainingDept();
				td.setDeptId(ids.get(i));
				td.setDeptName(names.get(i));
				td.setBusKey(trainPlan.getId());
				// td.setBeginTime(beginTime);
				// td.setEndTime(endTime);
				this.save(td);
			} else {
				TrainingDept td = this.getTrainDeptById(ids.get(i), trainPlan.getId());
				// td.setBeginTime(beginTime);
				// td.setEndTime(endTime);
				this.update(td);
			}
		}
	}

	/**
	 * 得到 项目编码（当前系统时间 年+月+日+001,002……） 然后再添加的时候保存。
	 * 
	 * @return
	 */
	private String getProjectId() {
		String currentYear = (new Date()).getYear() + 1900 + "";
		Date date = new Date();
		int month = date.getMonth() + 1;
		String a = String.valueOf(month);
		int day = date.getDate();
		String b = String.valueOf(day);
		String count = getCount();
		return currentYear + a + b + count;
	}

	/**
	 * 查询统计有多少个 培训计划（项目编码后3位的数字）
	 * 
	 * @return
	 */
	private String getCount() {
		String hql = "select count(*) from TrainingPlan";
		int a = this.queryForInt(hql) + 1;
		String str = String.valueOf(a);
		String n = null;
		if (str.length() == 1) {
			n = "00" + str;
		} else if (str.length() == 2) {
			n = "0" + str;
		} else {
			n = str;
		}
		return n;
	}

	/**
	 * 统计人数
	 * 
	 * @param id
	 * @return
	 */
	public int getCountUser(String id) {
		String hql = "select count(*) from TrainingUser where invalid=false and busKey=:id";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		int count = this.queryForInt(hql, map);
		return count;
	}
}
